package xyz.yang.toodles.util;

import java.util.function.Supplier;

import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

/**
 * @author Xuehong Yang
 * @since 1.0
 */
@SuppressWarnings("unused")
public final class Preconditions {
    public static final String ARGUMENT_EMPTY = "Argument expected not to be empty!";

    public static CharSequence checkNotNullOrEmpty(CharSequence s) {
        return checkNotNullOrEmpty(s, ARGUMENT_EMPTY);
    }

    public static CharSequence checkNotNullOrEmpty(CharSequence s, String message) {
        requireNonNull(s, message);
        if (s.isEmpty()) throwExceptionForBeingEmpty(message);
        return s;
    }

    public static <T> T[] checkNotNullOrEmpty(T[] array) {
        T[] checked = requireNonNull(array);
        if (checked.length == 0) throwExceptionForBeingEmpty();
        return checked;
    }

    public static void checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) {
        if (!expression) throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
    }

    public static void checkArgument(boolean expression, Supplier<String> errorMessage) {
        if (!expression) throw new IllegalArgumentException(errorMessage.get());
    }

    public static void checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) {
        if (!expression) {
            throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
        }
    }

    private Preconditions() {
    }

    private static void throwExceptionForBeingEmpty() {
        throwExceptionForBeingEmpty(ARGUMENT_EMPTY);
    }

    private static void throwExceptionForBeingEmpty(String message) {
        throw new IllegalArgumentException(message);
    }
}